<template>
  <div class="feature-detail-container">
    <div v-if="loading" class="feature-detail-loading">
      <n-skeleton height="60px" :repeat="1" />
      <n-skeleton text :repeat="3" class="mt-4" />
      <n-skeleton height="120px" :repeat="1" class="mt-4" />
    </div>
    
    <template v-else-if="feature">
      <div class="feature-detail-header">
        <n-breadcrumb>
          <n-breadcrumb-item>
            <router-link to="/">首页</router-link>
          </n-breadcrumb-item>
          <n-breadcrumb-item>
            <router-link :to="{name: 'feature-requests'}">功能请求</router-link>
          </n-breadcrumb-item>
          <n-breadcrumb-item>详情</n-breadcrumb-item>
        </n-breadcrumb>
        
        <div class="feature-title-wrapper">
          <h1 class="feature-title">{{ feature.title }}</h1>
          <div class="feature-meta">
            <StatusBadge :type="statusBadgeType" :text="statusText" />
            <span class="feature-date">提交于 {{ formatDate(feature.create_time) }}</span>
            <span class="feature-author">
              提交者: {{ feature.custom_name ? feature.custom_name : ((feature as any).user && (feature as any).user.username ? (feature as any).user.username : '匿名用户') }}
            </span>
          </div>
        </div>
      </div>
      
      <div class="feature-detail-body">
        <div class="feature-detail-content">
          <div class="feature-description">
            <div class="section-title">功能描述</div>
            <div class="section-content">
              <p v-html="formattedDescription"></p>
            </div>
          </div>
          
          <div v-if="feature.progress > 0" class="feature-progress">
            <div class="section-title">开发进度: {{ feature.progress }}%</div>
            <div class="progress-bar-container">
              <div 
                class="progress-bar-fill" 
                :style="{ width: `${feature.progress}%` }"
                :class="progressClass"
              ></div>
            </div>
          </div>
          
          <div v-if="feature.admin_note || feature.admin_remark" class="feature-admin-notes">
            <div class="section-title">管理回复</div>
            <div class="section-content admin-note">
              <p v-html="formattedAdminNote"></p>
            </div>
          </div>
        </div>
        
        <div class="feature-detail-sidebar">
          <div class="sidebar-card votes-card">
            <div class="sidebar-card-title">当前票数</div>
            <div class="votes-count">{{ feature.votes_count }}</div>
            <n-button 
              block 
              type="primary" 
              class="vote-button"
              :class="{'voted': feature.has_voted}"
              @click="handleVote"
              :disabled="isVoteDisabled"
            >
              {{ feature.has_voted ? '已投票' : '投票支持' }}
            </n-button>
            
            <div class="votes-limit-info">
              <p>今日已投票: {{ todayVotes }} / {{ maxVotesPerDay }}</p>
              <p v-if="feature.has_voted" class="text-success">您已为此功能投过票</p>
            </div>
          </div>
          
          <div class="sidebar-card">
            <div class="sidebar-card-title">最近更新</div>
            <div class="update-info">
              <p>最后更新: {{ formatDate(feature.update_time) }}</p>
              <p v-if="feature.status === FeatureRequestStatus.IN_PROGRESS">
                预计完成时间: {{ feature.expected_release_date || '暂无' }}
              </p>
            </div>
          </div>
        </div>
      </div>
      
      <div class="feature-detail-actions">
        <n-button @click="$router.push({name: 'feature-requests'})">
          返回列表
        </n-button>
      </div>
    </template>
    
    <template v-else>
      <n-result status="404" title="功能请求不存在" description="您查找的功能请求不存在或已被删除">
        <template #footer>
          <n-button @click="$router.push({name: 'feature-requests'})">
            返回列表
          </n-button>
        </template>
      </n-result>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { NButton, NBreadcrumb, NBreadcrumbItem, NResult, NSkeleton } from 'naive-ui'
import StatusBadge from '@/components/common/StatusBadge.vue'
import { getFeatureRequestDetail, voteFeatureRequest, getFeatureRequestsStatus } from '@/api/feature'
import { FeatureRequestDetail, FeatureRequestStatus } from '@/api/types/feature'

// 状态徽章类型
type StatusBadgeType = 'default' | 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'purple' | 'brown';

// 创建消息提示
const message = useMessage()
const route = useRoute()
const router = useRouter()

// 路由参数中的功能请求ID
const featureId = computed(() => Number(route.params.id))

// 加载状态
const loading = ref(true)

// 功能请求详情
const feature = ref<FeatureRequestDetail | null>(null)

// 统计数据
const todayVotes = ref(0)
const maxVotesPerDay = ref(10)

// 获取状态徽章类型
const statusBadgeType = computed<StatusBadgeType>(() => {
  if (!feature.value) return 'default'
  
  const typeMap: Record<number, StatusBadgeType> = {
    [FeatureRequestStatus.PENDING]: 'default',
    [FeatureRequestStatus.APPROVED]: 'primary',
    [FeatureRequestStatus.REJECTED]: 'danger',
    [FeatureRequestStatus.IN_PROGRESS]: 'warning',
    [FeatureRequestStatus.COMPLETED]: 'success',
    [FeatureRequestStatus.PLANNED]: 'info'
  }
  return typeMap[feature.value.status] || 'default'
})

// 获取状态文本
const statusText = computed(() => {
  if (!feature.value) return ''
  
  const textMap: Record<number, string> = {
    [FeatureRequestStatus.PENDING]: '待审核',
    [FeatureRequestStatus.APPROVED]: '已批准',
    [FeatureRequestStatus.REJECTED]: '已拒绝',
    [FeatureRequestStatus.IN_PROGRESS]: '开发中',
    [FeatureRequestStatus.COMPLETED]: '已完成',
    [FeatureRequestStatus.PLANNED]: '计划中'
  }
  return textMap[feature.value.status] || '未知状态'
})

// 获取进度条样式
const progressClass = computed(() => {
  if (!feature.value) return ''
  
  if (feature.value.status === FeatureRequestStatus.COMPLETED) {
    return 'progress-completed'
  }
  if (feature.value.status === FeatureRequestStatus.IN_PROGRESS) {
    return 'progress-in-progress'
  }
  if (feature.value.status === FeatureRequestStatus.PLANNED) {
    return 'progress-planned'
  }
  return ''
})

// 判断投票按钮是否禁用
const isVoteDisabled = computed(() => {
  if (!feature.value) return true
  
  return feature.value.has_voted || 
         feature.value.status === FeatureRequestStatus.REJECTED ||
         feature.value.status === FeatureRequestStatus.COMPLETED
})

// 格式化描述（将换行符转换为<br>）
const formattedDescription = computed(() => {
  if (!feature.value?.description) return ''
  return feature.value.description.replace(/\n/g, '<br>')
})

// 格式化管理员备注
const formattedAdminNote = computed(() => {
  const adminNote = feature.value?.admin_note || feature.value?.admin_remark
  if (!adminNote) return ''
  return adminNote.replace(/\n/g, '<br>')
})

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 加载功能请求详情
const loadFeatureDetail = async () => {
  if (!featureId.value) {
    feature.value = null
    loading.value = false
    return
  }
  
  loading.value = true
  
  try {
    const response = await getFeatureRequestDetail(featureId.value)
    
    if (response.code === 1) {
      feature.value = response.data
    } else {
      message.error(response.message || '获取功能请求详情失败')
      feature.value = null
    }
  } catch (error) {
    console.error('加载功能请求详情失败:', error)
    message.error('加载功能请求详情失败')
    feature.value = null
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getFeatureRequestsStatus()
    
    if (response.code === 1) {
      todayVotes.value = response.data.today_votes || 0
      
      if ('max_daily_votes' in response.data) {
        maxVotesPerDay.value = (response.data as any).max_daily_votes || 10
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 处理投票
const handleVote = async () => {
  if (!feature.value || isVoteDisabled.value) return
  
  try {
    const response = await voteFeatureRequest(feature.value.id)
    
    if (response.code === 1) {
      // 投票成功
      message.success('投票成功')
      feature.value.votes_count = response.data.votes_count
      feature.value.has_voted = true
      todayVotes.value++
    } else {
      message.error(response.msg || '投票失败')
    }
  } catch (error) {
    console.error('投票出错:', error)
    message.error('投票出错，请稍后重试'+error)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadFeatureDetail()
  loadStats()
})
</script>

<style scoped>
.feature-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.feature-detail-loading {
  padding: 2rem 0;
}

.mt-4 {
  margin-top: 1rem;
}

.feature-detail-header {
  margin-bottom: 2rem;
}

.feature-title-wrapper {
  margin-top: 1.5rem;
}

.feature-title {
  font-size: 2rem;
  font-weight: 700;
  color: var(--n-text-color-1);
  margin-bottom: 0.75rem;
}

.feature-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  align-items: center;
  margin-bottom: 1rem;
}

.feature-date, .feature-author {
  font-size: 0.875rem;
  color: var(--n-text-color-3);
}

.feature-detail-body {
  display: flex;
  flex-wrap: wrap;
  gap: 2rem;
  margin-bottom: 2rem;
}

.feature-detail-content {
  flex: 1;
  min-width: 0;
  max-width: 100%;
}

.feature-detail-sidebar {
  width: 300px;
}

@media (max-width: 768px) {
  .feature-detail-content, .feature-detail-sidebar {
    width: 100%;
  }
}

.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--n-text-color-1);
  margin-bottom: 0.75rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid var(--n-border-color);
}

.section-content {
  line-height: 1.6;
  color: var(--n-text-color-2);
  margin-bottom: 2rem;
}

.feature-description {
  margin-bottom: 2rem;
}

.feature-progress {
  margin-bottom: 2rem;
}

.progress-bar-container {
  height: 0.75rem;
  background-color: var(--n-border-color);
  border-radius: 0.375rem;
  overflow: hidden;
}

.progress-bar-fill {
  height: 100%;
  border-radius: 0.375rem;
  transition: width 0.3s ease;
}

.progress-completed {
  background-color: var(--n-success-color);
}

.progress-in-progress {
  background-color: var(--n-warning-color);
}

.progress-planned {
  background-color: var(--n-info-color);
}

.admin-note {
  padding: 1rem;
  background-color: var(--n-color-target);
  border-radius: 0.5rem;
  font-style: italic;
}

.sidebar-card {
  background-color: var(--n-card-color);
  border-radius: 0.5rem;
  padding: 1.25rem;
  margin-bottom: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--n-border-color);
}

.sidebar-card-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: var(--n-text-color-1);
  margin-bottom: 1rem;
}

.votes-card {
  text-align: center;
}

.votes-count {
  font-size: 2.5rem;
  font-weight: 700;
  color: var(--n-text-color-1);
  margin-bottom: 1rem;
}

.vote-button {
  margin-bottom: 1rem;
}

.voted {
  background-color: var(--n-success-color);
}

.votes-limit-info {
  font-size: 0.875rem;
  color: var(--n-text-color-3);
  margin-top: 0.5rem;
}

.update-info {
  font-size: 0.875rem;
  color: var(--n-text-color-2);
}

.update-info p {
  margin-bottom: 0.5rem;
}

.feature-detail-actions {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-start;
}

.text-success {
  color: var(--n-success-color);
}
</style> 